/**
 * Copyright 2011 Brigham Young University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.byu.nlp.data;

import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.RealMatrixPreservingVisitor;

import com.google.common.base.Preconditions;

/**
 * Utility methods for building feature matrices and instances.
 * 
 * @author rah67
 *
 */
public class FeatureMatrices {

	private static class Array2dFeatureMatrix extends Array2DRowRealMatrix implements FeatureMatrix {

		private static final long serialVersionUID = 1L;

		public Array2dFeatureMatrix(double[][] arr, boolean copy) throws IllegalArgumentException,
				NullPointerException {
			super(arr, copy);
		}

		@Override
		public void walkSparselyInColumnOrder(RealMatrixPreservingVisitor visitor) {
			walkInColumnOrder(visitor);
		}

		@Override
		public void walkSparselyInOptimizedOrder(RealMatrixPreservingVisitor visitor) {
			walkInOptimizedOrder(visitor);
		}

		@Override
		public void walkSparselyInRowOrder(RealMatrixPreservingVisitor visitor) {
			walkInRowOrder(visitor);
		}
	}
	
	/**
	 * Creates a new feature matrix from a two-dimensional array WITHOUT copying the array.
	 */
	public static FeatureMatrix newFeatureMatrix(double[][] data) {
		return new Array2dFeatureMatrix(data, false); 
	}

	/**
	 * Creates a new feature matrix from a two-dimensional array.
	 * 
	 * @param data the feature matrix in row-major order
	 * @param copy indicates whether the matrix is copied into the feature matrix
	 */
	public static FeatureMatrix newFeatureMatrix(double[][] data, boolean copy) {
		return new Array2dFeatureMatrix(data, copy); 
	}
	
	/**
	 * Creates a new instance using the specified label the two-dimensional array as features.
	 */
	public static LabeledInstance newInstance(double[][] data, int label) {
		Preconditions.checkNotNull(data);
		Preconditions.checkArgument(label < data.length);
		return new LabeledInstance(newFeatureMatrix(data), label);
	}
}
